package com.itheima.test02;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(10086);

        //线程池
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                5,
                10,
                3,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );

        while (true){
            Socket socket = serverSocket.accept();
            Thread t = new Thread(new MyThread(socket));
            pool.submit(t);
        }
        //serverSocket.close();
    }
}

//线程类
class MyThread implements Runnable{
private Socket socket;

    public MyThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        InputStream is = null;
        OutputStream os = null;
        try {
            //获得网络输入流
            is = socket.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

            //随机id
            String[] split = UUID.randomUUID().toString().split("-");
            //String substring = UUID.randomUUID().toString().replace("-", "").substring(0, 5);
            //本地输出流
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("exam2\\test02\\"+split[0]+".jpg"));

            //读--写
            int b ;
            while ((b = bis.read())!=-1){
                bos.write(b);
            }
            bos.flush();
            bos.close();

            //回复
            //网络输出流
            os = socket.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            bw.write("文件上传成功");
            bw.flush();
            bw.close();

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}